<?php

namespace App\Http\Controllers\Frontend\Auth;

use App\Http\Controllers\Frontend\FrontendController;
use App\Http\Resources\Frontend\ApiResource;
use App\Models\User;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\Request;

class VerificationController extends FrontendController
{

    public function __construct()
    {
        $this->middleware(['auth:' . $this->guard, 'captcha.verify'], ['except' => ['verify']]);
    }

    /**
     *
     * @param  \Illuminate\Http\Request  $request
     * @return ApiResource
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function verify(Request $request)
    {
        $id = $request->route('id');

        $user = User::find($id);

        if(!$user) {
            return new ApiResource('用户不存在', 0);
        }

        \Auth::login($user);
        
        if (! hash_equals((string) $request->route('id'), (string) $request->user()->getKey())) {
            throw new AuthorizationException;
        }

        if (! hash_equals((string) $request->route('hash'), sha1($request->user()->getEmailForVerification()))) {
            throw new AuthorizationException;
        }

        if ($request->user()->hasVerifiedEmail()) {
            return new ApiResource('邮箱已经验证通过了', 0);
        }

        if ($request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        }

        return new ApiResource('邮箱验证成功');
    }

    /**
     * @param Request $request
     * @return ApiResource
     */
    public function resend(Request $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return new ApiResource('邮箱已经验证通过了', 0);
        }

        $request->user()->sendEmailVerificationNotification();

        return new ApiResource('邮件发送成功');
    }
}
